/**
 * Copyright (c) <2010>, <SUNNY GUPTA>
 * All rights reserved.

 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of the <ORGANIZATION> nor the
 *     names of its contributors may be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <SUNNY GUPTA> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.gwtp.investmentadvisor.shared.entities;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.google.inject.Inject;
import com.gwtp.investmentadvisor.client.common.ClientCookieHelper;
import com.gwtp.investmentadvisor.client.dispatch.DispatchCallback;
import com.gwtp.investmentadvisor.shared.action.VerifyUserSession;
import com.gwtp.investmentadvisor.shared.action.VerifyUserSessionResult;
import com.gwtplatform.dispatch.client.DispatchAsync;

/**
 * 
 * @author sunny
 *
 */
public class CurrentUser extends DispatchCallback<VerifyUserSessionResult> implements Serializable {

  private static final long serialVersionUID = -7178031734142461362L;

  /**
   * Dispatch service for server communication.
   */
  private final DispatchAsync dispatcher;
    
  private String username;
  
  private String sessionID;
  
  private List<UserRole> userRoles;

  private boolean serverCallActive;
  
  private List<ServerCallback> callbackList;
  
  /**
   * 
   * @author sunny
   *
   */
  public interface ServerCallback {
    void onComplete(CurrentUser currentUser);
  }
  
  /**
   * TODO: Implement some form of timer based periodic checking to validate session.
   * TODO: Raise events when the state of current user changes from valid to invalid and vice versa
   */
  @Inject
  public CurrentUser(final DispatchAsync dispatcher) {
    this.dispatcher = dispatcher;
    
    this.serverCallActive = false;
    
    this.callbackList = new ArrayList<ServerCallback>();
  }

  /**
   * This async method should be called to validate the CurrentUser from server.
   * @param callback
   */
  public void validateFromServer(ServerCallback callback) {
    // If server call active, just register callback and return
    if (serverCallActive) {
      this.callbackList.add(callback);
      return;
    }
    
    // Obtain session ID
    String vSessionID = ClientCookieHelper.getSessionID();
            
    // check for null
    if (vSessionID != null) {      
      serverCallActive = true;
      this.callbackList.add(callback);
      //  that sessionID is valid
      dispatcher.execute(new VerifyUserSession(vSessionID), this);      
    } else {      
      // No cookie found, leave user uninitialized
      this.callbackList.add(callback);
      performCallback();
    }
  }
  
  public void resetCurrentUser(LoginAuthenticationInfo sessionInfo) {
    // Check for null
    if (sessionInfo != null) {
      setSessionID(sessionInfo.getSessionID());
      setUsername(sessionInfo.getUsername());
      setUserRoles(sessionInfo.getUserRoles());
    } else {
      setSessionID(null);
      setUsername(null);
      setUserRoles(null);
    }
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getUsername() {
    return username;
  }

  public void setSessionID(String sessionID) {
    this.sessionID = sessionID;
  }

  public String getSessionID() {
    return sessionID;
  }

  public void setUserRoles(List<UserRole> userRoles) {
    this.userRoles = userRoles;
  }

  public List<UserRole> getUserRoles() {
    return userRoles;
  }

  public void updateSessionCookie() {
    // Set cookie with sessionID
    ClientCookieHelper.setSessionID(this.sessionID);
  }

  @Override
  public void callback(VerifyUserSessionResult result) {
    LoginAuthenticationInfo sessionInfo = result.getLoginAuthenticationInfo();

    // Initialize based on server result & re-confirm that sessionIDs match & that user is authenticated
    if (sessionInfo != null && sessionInfo.isAuthenticated()) {
      // Now match session ID
      String serverReturnedSessionID = sessionInfo.getSessionID();
      // No need to match session ID if current session ID is null
      if (sessionID == null || (serverReturnedSessionID != null
          && serverReturnedSessionID.equals(sessionID))) {
        resetCurrentUser(sessionInfo);
      }
    }
    
    serverCallActive = false;
    
    performCallback();
  }
  
  @Override
  public void callbackError(Throwable t) {
    // Do nothing, but need to override to suppress any default action
    serverCallActive = false;
    
    performCallback();
  }

  private void performCallback() {
    // Exceute callbacks and unregister
    for (ServerCallback callback : callbackList) {
      callback.onComplete(this);
    }
    // Remove all
    callbackList.clear();
  }

  /**
   * Checks if the current user has a valid user role.
   * @return
   */
  public boolean hasValidRole() {
    // Return false if server call active or user roles is empty
    if (serverCallActive) {
      return false;
    } else {
      if (this.userRoles == null) {
        return false;
      } else {
        if (this.userRoles.size() == 0) {
          return false;
        }
      }
      // Valid, return true
      return true;
    }
  }

  public boolean isUserLoggedIn() {
    // Return false if server call active or user roles is empty
    if (serverCallActive || (this.userRoles == null || this.userRoles.size() == 0)) {
      return false;
    } else {
      return this.userRoles.contains(UserRole.USER);
    }
  }
  
  @Override
  public boolean equals(Object obj) {
    // Username uniquely identifies the user
    return this.username.equals(((CurrentUser) obj).getUsername());
  }
  
  @Override
  public int hashCode() {
    // Username uniquely identifies the user
    return this.username.hashCode();
  }
}
